"""训练系统路由"""
from fastapi import APIRouter, HTTPException, Body
from typing import Dict, Any, Optional
from app.services.training_service import training_service

router = APIRouter()


@router.post("/training/start")
async def start_training_session(
    user_id: str = Body(...),
    plan_id: Optional[str] = Body(None)
):
    """开始训练会话"""
    session = await training_service.create_session(user_id, plan_id)
    return session


@router.get("/training/question/{session_id}")
async def get_next_question(session_id: str, question_id: Optional[str] = None):
    """获取下一个训练题目"""
    from fastapi import Query
    
    # 如果指定了question_id，直接从题库获取
    if question_id:
        from app.db.question_bank import get_question_by_id
        import json
        import re
        question_data = get_question_by_id(question_id)
        if question_data:
            # 自动修正题目类型
            question_type = question_data.get("type", "single_choice")
            correct_answer = question_data.get("correct_answer", "")
            
            def extract_options_count(answer_text: str) -> int:
                """从答案文本中提取选项数量"""
                if not answer_text:
                    return 0
                try:
                    if answer_text.strip().startswith('['):
                        data = json.loads(answer_text)
                        if isinstance(data, list):
                            return len(data)
                except:
                    pass
                matches = re.findall(r'选项([A-D])', answer_text)
                return len(set(matches))
            
            correct_options_count = extract_options_count(correct_answer)
            if correct_options_count > 1 and question_type == "single_choice":
                question_type = "indefinite_choice"
            
            return {
                "question_id": question_data.get("question_id"),
                "session_id": session_id,
                "content": question_data.get("content"),
                "options": question_data.get("options", []),
                "type": question_type,  # 使用修正后的类型
                "difficulty": question_data.get("difficulty", "medium"),
                "knowledge_points": question_data.get("knowledge_points", []),
                "category": question_data.get("category"),
                "subject": question_data.get("subject")
            }
    
    # 从session_id提取user_id（简化实现，实际应从数据库查询）
    user_id = session_id.split('_')[1] if '_' in session_id else "user_001"
    question = await training_service.get_next_question(session_id, user_id)
    return question


@router.get("/training/question-by-id/{question_id}")
async def get_question_by_id(question_id: str):
    """根据题目ID直接获取题目"""
    from app.db.question_bank import get_question_by_id as get_q
    
    question_data = get_q(question_id)
    if not question_data:
        raise HTTPException(status_code=404, detail="题目不存在")
    
    # 自动修正题目类型
    import json
    import re
    question_type = question_data.get("type", "single_choice")
    correct_answer = question_data.get("correct_answer", "")
    
    def extract_options_count(answer_text: str) -> int:
        """从答案文本中提取选项数量"""
        if not answer_text:
            return 0
        try:
            if answer_text.strip().startswith('['):
                data = json.loads(answer_text)
                if isinstance(data, list):
                    return len(data)
        except:
            pass
        matches = re.findall(r'选项([A-D])', answer_text)
        return len(set(matches))
    
    correct_options_count = extract_options_count(correct_answer)
    if correct_options_count > 1 and question_type == "single_choice":
        question_type = "indefinite_choice"
    
    return {
        "question_id": question_data.get("question_id"),
        "content": question_data.get("content"),
        "options": question_data.get("options", []),
        "type": question_type,  # 使用修正后的类型
        "difficulty": question_data.get("difficulty", "medium"),
        "knowledge_points": question_data.get("knowledge_points", []),
        "category": question_data.get("category"),
        "subject": question_data.get("subject"),
        "correct_answer": question_data.get("correct_answer"),  # 注意：实际应该隐藏
        "explanation": question_data.get("explanation")  # 注意：实际应该隐藏
    }


@router.post("/training/submit")
async def submit_answer(
    session_id: str = Body(...),
    question_id: str = Body(...),
    answer: Dict[str, Any] = Body(...),
    time_spent: float = Body(0)
):
    """提交答案"""
    user_answer = answer.get("answer", "")
    if not user_answer:
        raise HTTPException(status_code=400, detail="答案不能为空")
    
    result = await training_service.submit_answer(
        session_id, question_id, user_answer, time_spent
    )
    return result


@router.post("/training/reset-session/{session_id}")
async def reset_session(session_id: str):
    """重置训练会话（清空已做题目记录，可以重新开始）"""
    from app.core.database import RedisClient
    
    try:
        redis = RedisClient.get_client()
        redis.ping()
        # 删除已做题目记录
        session_questions_key = f"session_questions:{session_id}"
        redis.delete(session_questions_key)
        return {
            "session_id": session_id,
            "status": "reset",
            "message": "会话已重置，可以重新开始训练"
        }
    except Exception as e:
        # 如果Redis不可用，返回成功（内存存储会在新会话时自动清空）
        return {
            "session_id": session_id,
            "status": "reset",
            "message": "会话已重置（内存存储）"
        }


@router.post("/training/analyze-error")
async def analyze_error(
    session_id: str = Body(...),
    question_id: str = Body(...)
):
    """错误分析"""
    from app.ai.evaluation_engine import get_evaluation_engine
    evaluation_engine = get_evaluation_engine()
    
    # 模拟题目和答案数据（实际应从数据库获取）
    question_content = "某公司因合同纠纷提起诉讼，以下哪个选项是正确的？"
    user_answer = "选项A"
    correct_answer = "选项C"
    
    error_analysis = await evaluation_engine.classify_error_type(
        question_content, user_answer, correct_answer
    )
    
    return {
        "session_id": session_id,
        "question_id": question_id,
        "error_type": error_analysis["error_type"],
        "error_category": error_analysis["error_category"],
        "error_details": error_analysis.get("details", {}),
        "recommendations": [
            "复习相关法律条文",
            "练习相关类型的案例题目"
        ]
    }


@router.get("/training/plan/{plan_id}")
async def get_training_plan(plan_id: str):
    """获取训练计划详情"""
    # 模拟训练计划数据（实际应从数据库查询）
    return {
        "plan_id": plan_id,
        "status": "active",
        "progress": {
            "completed_days": 15,
            "total_days": 180,
            "completion_rate": 8.3
        },
        "statistics": {
            "total_questions": 450,
            "correct_answers": 315,
            "accuracy_rate": 70.0
        }
    }
